#include "Config.h"

#include <fstream>
#include <algorithm>

void Config::Initialise()
{
	ifstream File("./.mimeconfig", ifstream::in);
	if(!File.is_open())
	{
		cout << "Config failed to load. Using default mime types" << endl;
		Loaded = false;
		return;
	}
	string Line;
	char* cLine;
	size_t Pos;
	while(!File.eof())
	{
		cLine = new char[512];
		File.getline(cLine, 512);
		Line = cLine;

		Pos = Line.find(": ");

		mFileMimes.push_back(pair<string, string>(Line.substr(0, Pos), Line.substr(Pos + 2)));
		delete [] cLine;
	}
	Loaded = true;
}

Config::Config()
{
	Loaded = false;
}

Config::~Config()
{

}

bool Config::LookupFilePermissions(string File)
{
	return true;
}

string Config::LookupFileMime(string FileExt)
{
	transform(FileExt.begin(), FileExt.end(), FileExt.begin(), ::tolower);
	if(Loaded)
	{
		size_t Pos;
		for(auto it = mFileMimes.begin(); it != mFileMimes.end(); ++it)
		{
			Pos = it->first.find(FileExt);
			if(Pos != string::npos)
			{
				return it->second;
			}
		}
		for(auto it = mFileMimes.begin(); it != mFileMimes.end(); ++it)
		{
			Pos = it->first.find("Default");
			if(Pos != string::npos)
			{
				return it->second;
			}
		}
		// Return default if "Default" is missing from config file.
		return "application/octet-stream";
	}
	else
	{
		if(FileExt == ".jpg")
		{
			return "image/jpeg";
		}
		if(FileExt == ".jpeg")
		{
			return "image/jpeg";
		}
		if(FileExt == ".png")
		{
			return "image/png";
		}
		if(FileExt == ".gif")
		{
			return "image/gif";
		}
		if(FileExt == ".html")
		{
			return "text/html";
		}
		if(FileExt == ".css")
		{
			return "text/css";
		}
		if(FileExt == ".js")
		{
			return "application/x-javascript";
		}
		if(FileExt == ".htm")
		{
			return "text/html";
		}
        
		if(FileExt == ".lua")
		{
			return "Dynamic";
		}
		return "application/octet-stream";
	}
}
